package small.common.crypto.util;

import small.common.core.constants.CommonConstants;
import small.common.designPattern.create.singleton.SingletonRepository;
import small.common.core.util.StringUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author zhoujin
 * @Date 2022/11/25 13:27
 */
public class KeyUtil {

    /**
     * 获取key
     *
     * @param dataId
     * @param group
     * @return
     */
    public static String getKey(String dataId, String group) {
        if (StringUtil.isBlank(dataId) && StringUtil.isBlank(group)){
            return null;
        }
        return getKey(dataId,group,null);
    }

    /**
     * 获取key
     *
     * @param dataId
     * @param group
     * @param tenant
     * @return
     */
    public static String getKey(String dataId, String group, String tenant) {
        StringBuilder sb = new StringBuilder();
        urlEncode(dataId, sb);
        sb.append('+');
        urlEncode(group, sb);
        if (StringUtil.isNotEmpty(tenant)) {
            sb.append('+');
            urlEncode(tenant, sb);
        }
        return sb.toString();
    }

    /**
     * 解析key
     */
    public static String[] parseKey(String groupKey) {
        StringBuilder sb = new StringBuilder();
        String dataId = null;
        String group = null;
        String tenant = null;

        for (int i = 0; i < groupKey.length(); ++i) {
            char c = groupKey.charAt(i);
            if ('+' == c) {
                if (null == dataId) {
                    dataId = sb.toString();
                    sb.setLength(0);
                } else if (null == group) {
                    group = sb.toString();
                    sb.setLength(0);
                } else {
                    throw new IllegalArgumentException("invalid groupkey:" + groupKey);
                }
            } else if ('%' == c) {
                char next = groupKey.charAt(++i);
                char nextnext = groupKey.charAt(++i);
                if ('2' == next && 'B' == nextnext) {
                    sb.append('+');
                } else if ('2' == next && '5' == nextnext) {
                    sb.append('%');
                } else {
                    throw new IllegalArgumentException("invalid groupkey:" + groupKey);
                }
            } else {
                sb.append(c);
            }
        }

        if (StringUtil.isBlank(group)) {
            group = sb.toString();
            if (group.length() == 0) {
                throw new IllegalArgumentException("invalid groupkey:" + groupKey);
            }
        } else {
            tenant = sb.toString();
            if (group.length() == 0) {
                throw new IllegalArgumentException("invalid groupkey:" + groupKey);
            }
        }

        return new String[]{dataId, group, tenant};
    }

    /**
     * + -> %2B % -> %25.
     */
    static void urlEncode(String str, StringBuilder sb) {
        if (StringUtil.isBlank(str)){
            return;
        }
        for (int idx = 0; idx < str.length(); ++idx) {
            char c = str.charAt(idx);
            if ('+' == c) {
                sb.append("%2B");
            } else if ('%' == c) {
                sb.append("%25");
            } else {
                sb.append(c);
            }
        }
    }

    /**
     * 拼凑key和value
     */
    public static StringBuilder appendKeyAndValue(String key,String value, StringBuilder builder) {
        StringBuilder res = builder;
        if (builder == null) {
            res = new StringBuilder();
        }
        res.append(key).append(CommonConstants.WORD_SEPARATOR);
        res.append(value).append(CommonConstants.LINE_SEPARATOR);
        return res;
    }

    /**
     * 拼凑key和value的Map集合
     */
    public static StringBuilder appendKeyAndValueMap(Map<String,String> map, StringBuilder builder) {
        if (map == null){
            throw new IllegalArgumentException("map is null");
        }
        StringBuilder res = builder;
        if (builder == null) {
            res = new StringBuilder();
        }
        for (Map.Entry<String, String> entry : map.entrySet()) {
            appendKeyAndValue(entry.getKey(),entry.getValue(),builder);
        }
        return res;
    }

    /**
     *
     * 解析key和value拼凑String
     *
     * @param configKeysString
     * @return
     */
    public static Map<String, String> parseKeyMap(String configKeysString) {

        Map<String, String> md5Map = new HashMap<String, String>(5);

        if (null == configKeysString || "".equals(configKeysString)) {
            return md5Map;
        }
        int start = 0;
        String tmpStr = null;
        for (int i = start; i < configKeysString.length(); i++) {
            char c = configKeysString.charAt(i);
            if (c == CommonConstants.WORD_SEPARATOR_CHAR) {
                tmpStr = configKeysString.substring(start, i);
                start = i + 1;
            } else if (c == CommonConstants.LINE_SEPARATOR_CHAR) {
                String endValue = "";
                if (start + 1 <= i) {
                    endValue = configKeysString.substring(start, i);
                }
                start = i + 1;
                String groupKey = (String) SingletonRepository.SingletonData.getSingleton(tmpStr);
                md5Map.put(groupKey, endValue);
                tmpStr = null;
                // Protect malformed messages
                if (md5Map.size() > 10000) {
                    throw new IllegalArgumentException("invalid protocol, too much listener");
                }
            }
        }
        return md5Map;
    }

    public static void main(String[] args) {
        String key = getKey("", "11");
        System.out.println("getKey:"+key);

    }

}
